from django.shortcuts import render,redirect
from .models import CartInfo
from django.http import JsonResponse
from df_user import user_decorator
# Create your views here.

@user_decorator.login
def cart(request):
    uid = request.session['user_id']
    carts =CartInfo.objects.filter(user_id=uid)
    context = {
        'title':'购物车',
        'page_name':1,
        'carts':carts
    }
    return render(request, 'df_cart/cart.html', context)

@user_decorator.login
def add(request, gid, count):

    uid = request.session['user_id'] #获取用户id
    
    gid = int(gid)#获取商品id
    count = int(count) #获取商品数量
  
    #查询该用户的购物车中是否已经有此商品，如果有则数量增加，没有则新增
    carts = CartInfo.objects.filter(user_id=uid, goods_id=gid)
    if len(carts) >=1:
        cart = carts[0]
        cart.count = cart.count + count
    else:
        cart = CartInfo()
        cart.user_id = uid
        cart.goods_id = gid
        cart.count = count
    cart.save()
    #如果是ajax（）请求则返回json,否则转向购物车
    # print(request.is_ajax())
    if request.is_ajax():
        count = CartInfo.objects.filter(user_id=uid).count()
        
        return JsonResponse({'count':count})
    else:
        return redirect('/cart/cart')

def delete(request, cart_id):
    cart_id = int(cart_id)
    cart = CartInfo.objects.get(id = cart_id).delete()
    count = CartInfo.objects.all().count()
    
    return JsonResponse({'ok':1, 'count':count})


def delete_all(request):
    carts = CartInfo.objects.all()
    for cart in carts:
        cart.delete()
    return redirect('/cart/cart')


def edit(request, cart_id,count):

    cart_id = int(cart_id)
    count = int(count) #获取商品数量

    carts = CartInfo.objects.filter(id=cart_id).update(count=count)
    
    return JsonResponse({'status':1})